--可以随时暂停启动，不会关闭应用重新启动 2015.08
--第4个兵营不会造哥布林，造弓箭手  2015.08
--修复是否使用狂暴药水，设置使用时会制造药水，不使用则不造  2015.09
--搜索卡死次数由30->300  2015.10
--增加死鱼模式，修改造兵方式，固定野蛮人数量 2015.10.15
--有情况大概30多s会重连、先判兵营是否满 2015.10.17
--增加偷本模式 2015.11.06
--@author xiaodujw@126.com

init("0", 2)
luaExitIfCall(true)

initLog("goblin", 0)

-- ------------------------------------------------
function getScreenType()
    SCREEN_HEIGHT, SCREEN_WIDTH = getScreenSize()
    local k = SCREEN_WIDTH / SCREEN_HEIGHT
    if SCREEN_HEIGHT == 640 and SCREEN_WIDTH == 1136 then
        return "16_9_iPhone5"
    elseif math.abs(k - 16 / 9) < 0.01 then
        return "16_9_iPhone6"
    elseif math.abs(k - 4 / 3) < 0.01 then
        return "4_3"
    elseif math.abs(k - 3 / 2) < 0.01 then
        return "3_2"
    end
end

-- --------------初始化常量--------------------------
DEVICE_TYPE, SCREEN_TYPE,  TS_VER, OS_VER = getDeviceType(), getScreenType(),  getTSVer(), getOSVer()
SCREEN_HEIGHT, SCREEN_WIDTH = getScreenSize()
COCAPP_IDENTIFIER = "com.supercell.magic"
COCXXZHUSHOU_IDENTIFIER = "com.flamingo.XXAssitant"
BARRACKS_NUMBER = 4
setting_ifdonate = true
setting_ifrequest = true
setting_ifuseRageSpell = true
setting_ifdeadFish = true
setting_iftouben = false
setting_campDegree = 9
--每个兵营黄毛制造数量
trainBarbarianCount=17
needtrain = 1 
-- --------------初始化常量--------------------------

-- --------------以下为点的配置--------------------------
-- x, y, r, g, b
conf_3_2 = {
    -- loading页面
    ["loadpage_1"] = { 100, 100, 0, 0, 0 },
    ["loadpage_2"] = { 200, 200, 0, 0, 0 },
    ["loadpage_3"] = { 183,579,57,44,57 },
    ["loadpage_4"] = { 699,576,57,44,57 },
    -- 部落站页面
    ["clanwar_1"] = {52,536,107,48,33},
--    { 34, 476, 0, 65, 156 },
--    ["clanwar_2"] = { 58, 476, 0, 65, 156 },

    -- 捐兵打开
    ["donate_1"] = { 451, 247, 247, 166, 66 },
    ["donate_2"] = { 392, 21, 0, 0, 0 },

    -- 右切换
    ["train_switch_right"] = { 904,310,247,130,57 },

    -- 普通兵营
    ["barracks_1"] = { 904,310,247,130,57 },
    ["barracks_2"] = { 363,299,239,65,115 },

    -- 暗黑兵营
    ["darkbarracks_1"] = { 904,310,247,130,57 },
    ["darkbarracks_2"] = { 344,270,8,16,8 },

    -- 药水工厂
    ["spellfactory_1"] = { 904,310,247,130,57 },
    ["spellfactory_2"] = { 476,327,66,32,99 },


    -- 搜索页面
    ["searchmatch"] = { 180, 200, 250, 250, 250 },

    -- 攻击前
    ["beforeattack_1"] = {37,465,239,81,82},
    ["beforeattack_2"] = {124,467,239,81,82},

    -- 攻击后
    ["afterattack_1"] = {428,591,90,174,16},
    ["afterattack_2"] = {527,585,99,178,16},


    -- returnHome button
    ["returnHomeButton"] = { 29,546,239,227,206 },

    -- attack button
    ["attackbutton"] = { 71,545,156,65,16 },


    -- cancelTrain Button
    ["cancelTrainButton"] = { 574,115,247,130,140 },

    -- rightTopCorner
    ["rightTopCorner"] = { 862,40,123,109,33 },

    -- rightDownBarracks
    ["rightDownBarracks"] = { 55,448,239,166,49 },


    -- trainAnchor
    ["trainAnchor"] = { 363,299,239,65,115 },

    -- trainBarbarian
    ["trainBarbarian"] = { 213,275,255,251,49 },

    -- trainGiant
    ["trainGiant"] = { 490,315,255,223,165 },

    -- trainWallBreaker
    ["trainWallBreaker"] = { 735,339,16,24,16 },

    -- trainGoblin
    ["trainGoblin"] = { 629,278,189,247,107 },

    -- makeRageSpell
    ["makeRageSpell"] = { 476,327,66,32,99 },


    -- fullMark
    ["fullMark"] = { 786, 179, 239, 235, 231 },


    -- findMatchButton
    ["findMatchButton"] = { 159,526,222,69,0 },

    -- confirmGo
    ["confirmGo"] = { 605, 384, 214, 239, 123 },


    -- myhomemark
    ["myHomeMark"] = {   18,302,214,77,24 },
    --{ 601,27,247,251,255 },


    -- alert Button
    ["alertButton"] = { 500, 400, 233, 233, 233 },




    --castleRequest
    ["castleRequest"] = {834, 272, 214, 235, 123},
    ["castleRequest_1"] = {823,259,214,239,132 },
    ["castleRequest_YES"] = {667,325,90,174,16 },


    --reinforce
    ["reinforce_open"] = {   18,302,214,77,24 },
    ["reinforce_left"] = {36,227,57,65,57},
    ["reinforce_right"] = {109,245,66,69,66},
    ["reinforce_tab"] = {  321,   22, 0x736d52, 0, 0},
    ["reinforce_btn"] = {244,300,99,174,16},
    ["reinforce_anchor"] = {410,178,239,65,115},




    -- 新的造兵
    ["n_summary"] = {121, 580, 0, 0, 0},

    ["n_barrack_avalible_1"] = {235, 604, 140, 130, 115},
    ["n_barrack_idle_1"] = {271, 560, 140, 130, 115},

    ["n_barrack_avalible_2"] = {304, 602, 140, 130, 115},
    ["n_barrack_idle_2"] = {351, 568, 140, 130, 115},

    ["n_barrack_avalible_3"] = {383, 608, 140, 130, 115},
    ["n_barrack_idle_3"] = {425, 562, 140, 130, 115},

    ["n_barrack_avalible_4"] = {466, 605, 140, 130, 115},
    ["n_barrack_idle_4"] = {505, 566, 140, 130, 115},


    ["n_spellfactory_avalible"] = {746, 568, 140, 130, 115},
    ["n_spellfactory_idle"] = {797, 565, 140, 130, 115},
}

conf_16_9 = {
    -- loading页面
    ["loadpage_1"] = { 100, 100, 0, 0, 0 },
    ["loadpage_2"] = { 200, 200, 0, 0, 0 },
    ["loadpage_3"] = { 170, 570, 49, 40, 49 },
    ["loadpage_4"] = { 960, 570, 66, 48, 57 },
    -- 部落站页面
    ["clanwar_1"] = {51,535,107,48,33 },
--    { 34, 476, 0, 65, 156 },
--    ["clanwar_2"] = { 58, 476, 0, 65, 156 },

    -- 捐兵打开
    ["donate_1"] = { 451, 247, 247, 166, 66 },
    ["donate_2"] = { 392, 21, 0, 0, 0 },

    -- 右切换
    ["train_switch_right"] = { 989, 314, 247, 130, 57 },

    -- 普通兵营
    ["barracks_1"] = { 144, 310, 247, 130, 57 },
    ["barracks_2"] = { 448, 299, 239, 65, 115 },

    -- 暗黑兵营
    ["darkbarracks_1"] = { 144, 310, 247, 130, 57 },
    ["darkbarracks_2"] = { 433, 272, 8, 16, 16 },

    -- 药水工厂
    ["spellfactory_1"] = { 144, 310, 247, 130, 57 },
    ["spellfactory_2"] = { 564, 327, 66, 32, 99 },


    -- 搜索页面
    ["searchmatch"] = { 180, 200, 250, 250, 250 },

    -- 攻击前
    ["beforeattack_1"] = { 131, 470, 239, 81, 82 },
    ["beforeattack_2"] = { 34, 467, 239, 81, 82 },

    -- 攻击后
    ["afterattack_1"] = { 630, 591, 90, 174, 16 },
    ["afterattack_2"] = { 498, 587, 90, 174, 16 },


    -- returnHome button
    ["returnHomeButton"] = { 46, 531, 247, 166, 49 },

    -- attack button
    ["attackbutton"] = { 35, 524, 247, 166, 49 },


    -- cancelTrain Button
    ["cancelTrainButton"] = { 662, 115, 247, 130, 140 },

    -- rightTopCorner
    ["rightTopCorner"] = { 1098, 31, 250, 250, 250 },

    -- rightDownBarracks
    ["rightDownBarracks"] = { 57, 445, 239, 166, 49 },


    -- trainAnchor
    ["trainAnchor"] = { 448, 299, 239, 65, 115 },

    -- trainBarbarian
    ["trainBarbarian"] = { 300, 275, 255, 251, 49 },

    -- trainGiant
    ["trainGiant"] = { 575, 315, 255, 223, 165 },

    -- trainWallBreaker
    ["trainWallBreaker"] = { 826, 338, 16, 24, 16 },

    -- trainGoblin
    ["trainGoblin"] = { 716, 281, 189, 247, 107 },

    -- makeRageSpell
    ["makeRageSpell"] = { 564, 327, 66, 32, 99 },


    -- fullMark
    ["fullMark"] = { 905, 183, 239, 235, 231 },


    -- findMatchButton
    ["findMatchButton"] = { 173, 529, 222, 69, 0 },

    -- confirmGo
    ["confirmGo"] = { 605, 384, 214, 239, 123 },


    -- myhomemark
    ["myHomeMark"] = { 594, 30, 247, 247, 255 },


    -- alert Button
    ["alertButton"] = { 500, 400, 233, 233, 233 },




    --castleRequest
    ["castleRequest"] = {834, 272, 214, 235, 123},
    ["castleRequest_1"] = {917, 271, 214, 235, 123},
    ["castleRequest_YES"] = {734, 329, 90, 174, 16},


    --reinforce
    ["reinforce_open"] = {   17,  302, 214, 77, 24},
    ["reinforce_left"] = {   33,  225, 0x424542, 0, 0},

    ["reinforce_right"] = {   94,  250, 0x424542, 0, 0},
    ["reinforce_tab"] = {  321,   22, 0x736d52, 0, 0},
    ["reinforce_btn"] = {  182,  285, 198, 227, 90},
    ["reinforce_anchor"] = {  406,  169, 255, 93, 206},




    -- 新的造兵
    ["n_summary"] = {222, 585, 0, 0, 0},

    ["n_barrack_avalible_1"] = {323, 609, 140, 130, 115},
    ["n_barrack_idle_1"] = {362, 564, 140, 130, 115},

    ["n_barrack_avalible_2"] = {401, 609, 140, 130, 115},
    ["n_barrack_idle_2"] = {438, 564, 140, 130, 115},

    ["n_barrack_avalible_3"] = {475, 609, 140, 130, 115},
    ["n_barrack_idle_3"] = {518, 564, 140, 130, 115},

    ["n_barrack_avalible_4"] = {554, 609, 140, 130, 115},
    ["n_barrack_idle_4"] = {593, 564, 140, 130, 115},


    ["n_spellfactory_avalible"] = {839, 568, 140, 130, 115},
    ["n_spellfactory_idle"] = {883, 564, 140, 130, 115},
}

conf_4_3 = {
    -- loading页面
    ["loadpage_1"] = { 100, 100, 0, 0, 0 },
    ["loadpage_2"] = { 200, 200, 0, 0, 0 },
    ["loadpage_3"] = { 313, 1375, 57, 40, 57 },
    ["loadpage_4"] = { 1642, 1402, 57, 48, 57 },
    -- 部落站页面
    ["clanwar_1"] = {102,1331,107,48,33 },
--    { 69, 1212, 0, 65, 156 },
--    ["clanwar_2"] = { 118, 1212, 0, 65, 156 },

    -- 捐兵打开
    ["donate_1"] = { 789, 731, 247, 166, 66 },
    ["donate_2"] = { 716, 21, 0, 0, 0 },


    -- 右切换
    ["train_switch_right"] = { 1821, 754, 247, 130, 57 },

    -- 普通兵营
    ["barracks_1"] = { 224, 750, 247, 130, 57 },
    ["barracks_2"] = { 784, 693, 255, 89, 214 },

    -- 暗黑兵营
    ["darkbarracks_1"] = { 224, 750, 247, 130, 57 },
    ["darkbarracks_2"] = { 764, 678, 8, 16, 16 },

    -- 药水工厂
    ["spellfactory_1"] = { 224, 750, 247, 130, 57 },
    ["spellfactory_2"] = { 1018, 781, 66, 32, 99 },


    -- 搜索页面
    ["searchmatch"] = { 396, 347, 250, 250, 250 },

    -- 攻击前
    ["beforeattack_1"] = { 254, 1190, 239, 81, 82 },
    ["beforeattack_2"] = { 57, 1188, 239, 81, 82 },

    -- 攻击后
    ["afterattack_1"] = { 880, 1309, 90, 174, 16 },
    ["afterattack_2"] = { 1164, 1314, 90, 174, 16 },


    -- returnHome button
    ["returnHomeButton"] = { 57, 1291, 247, 243, 239 },

    -- attack button
    ["attackbutton"] = { 222, 1402, 156, 69, 24 },


    -- cancelTrain Button
--    ["cancelTrainButton"] = { 1202, 382, 247, 130, 140 },

    -- rightTopCorner
    ["rightTopCorner"] = { 1946, 92, 250, 250, 250 },

    -- rightDownBarracks
    ["rightDownBarracks"] = { 102, 1226, 156, 65, 24 },


    -- trainAnchor
    ["trainAnchor"] = { 784, 693, 255, 89, 214 },

    -- trainBarbarian
    ["trainBarbarian"] = { 514, 684, 255, 251, 49 },

    -- trainGiant
    ["trainGiant"] = { 1039, 760, 255, 223, 165 },

    -- trainWallBreaker
    ["trainWallBreaker"] = { 1498, 809, 16, 24, 16 },

    -- trainGoblin
    ["trainGoblin"] = { 1303, 696, 189, 247, 107 },

    -- makeRageSpell
    ["makeRageSpell"] = { 1018, 781, 66, 32, 99 },


    -- fullMark
--    ["fullMark"] = { 1604, 515, 239, 235, 231 },


    -- findMatchButton
    ["findMatchButton"] = { 609, 1231, 222, 69, 0 },

    -- confirmGo
    ["confirmGo"] = { 1316, 866, 214, 239, 123 },


    --reinforce
    ["reinforce_open"] = {   46,  844, 214, 77, 24},
    ["reinforce_left"] = {   77,  345, 0x424542},

    ["reinforce_right"] = {  427,  375, 0x424542},
    ["reinforce_tab"] = {  589,   31, 0x736d52, 0, 0},
    
    -- 新的造兵
    ["n_summary"] = {335, 1266, 0, 0, 0},

    ["n_barrack_avalible_1"] = {570, 1307, 140, 130, 115},
    ["n_barrack_idle_1"] = {625, 1229, 140, 130, 115},

    ["n_barrack_avalible_2"] = {704, 1307, 140, 130, 115},
    ["n_barrack_idle_2"] = {781, 1229, 140, 130, 115},

    ["n_barrack_avalible_3"] = {850, 1307, 140, 130, 115},
    ["n_barrack_idle_3"] = {920, 1229, 140, 130, 115},

    ["n_barrack_avalible_4"] = {994, 1307, 140, 130, 115},
    ["n_barrack_idle_4"] = {1071, 1229, 140, 130, 115},


    ["n_spellfactory_avalible"] = {1523, 1227, 140, 130, 115},
    ["n_spellfactory_idle"] = {1610, 1222, 140, 130, 115},
    
    ["end_fight"] = {95,1196,239,81,82},
    ["confirm_end_fight"] = {1298, 887, 206, 235, 107},
    ["find_next"] = {1774,1144,247,170,41},
    ["afterattack_1star_1"] = {1700,1210,214,215,206},
    ["afterattack_1star_2"] = {1700,1197,247,243,247},
    
    ["fullMark"] = {959,335,239,81,82},
    ["cancelTrainButton"] = { 1353,388,255,255,255 },
    ["gd_barbarian"] = {170,1385,255,182,33},
    
    --castleRequest
    ["castleRequest"] = {1679, 676, 214, 235, 123},
    ["castleRequest_1"] = {1696, 654, 214, 239, 140},
    ["castleRequest_2"] = {1564, 793, 132, 195, 24},
    ["castleRequest_YES"] = {1308, 573, 90, 174, 16},
    -- myhomemark
    ["myHomeMark"] = { 1394,84,74,142,0 },
    -- alert Button 841,856,230,218,213
    
    ["alertButton_1"] = { 839,850,223,224,204 },
    ["alertButton_2"] = { 910, 900, 233, 233, 233 },
    ["reinforce_btn"] = { 466,505,189,227,82},
    ["reinforce_anchor"] = {  1073,270,247,65,123},
    ["coc_start_pos"] = {1418,262,255,255,255},
    ["reinforce_ok_1_1"] = {844,1025,148,40,82},
    ["reinforce_ok_1_2"] = {890,1106,214,195,8},
    ["reinforce_ok_2_1"] = {978,1022,148,40,82},
    ["reinforce_ok_2_2"] = {1024,1105,214,199,0},
    ["reinforce_ok_3_1"] = {1146,776,239,65,115},
    ["reinforce_ok_3_2"] = {1158,852,214,199,0},
    
}

sbattack_conf = {

    ["3_2"] = {
        ["troop_button_startX"] = 0.010996 * SCREEN_WIDTH,
        ["troop_button_startY"] = 0.8234 * SCREEN_HEIGHT,
        ["troop_button_width"] = 0.0898145 * SCREEN_WIDTH,
        ["troop_button_height"] = 0.1587 * SCREEN_HEIGHT,
        ["set_troop_startX"] = 0.142 * SCREEN_WIDTH,
        ["set_troop_startY"] = 0.403 * SCREEN_HEIGHT,
        ["set_troop_endX"] = 0.391 * SCREEN_WIDTH,
        ["set_troop_endY"] = 0.145 * SCREEN_HEIGHT,
        ["set_troop_pointX"] = 0.276 * SCREEN_WIDTH,
        ["set_troop_pointY"] = 0.266 * SCREEN_HEIGHT,
        ["set_spell_pointX"] = 0.357 * SCREEN_WIDTH,
        ["set_spell_pointY"] = 0.364 * SCREEN_HEIGHT,
        
        ["set_troop_startX1"] = 0.142 * SCREEN_WIDTH,
        ["set_troop_startY1"] = 0.603 * SCREEN_HEIGHT,
        ["set_troop_endX1"] = 0.391 * SCREEN_WIDTH,
        ["set_troop_endY1"] = 0.855 * SCREEN_HEIGHT,
        ["set_troop_startX2"] = 0.858 * SCREEN_WIDTH,
        ["set_troop_startY2"] = 0.603 * SCREEN_HEIGHT,
        ["set_troop_endX2"] = 0.609 * SCREEN_WIDTH,
        ["set_troop_endY2"] = 0.855 * SCREEN_HEIGHT,
        ["set_troop_startX3"] = 0.609 * SCREEN_WIDTH,
        ["set_troop_startY3"] = 0.145 * SCREEN_HEIGHT,
        ["set_troop_endX3"] = 0.855 * SCREEN_WIDTH,
        ["set_troop_endY3"] = 0.403 * SCREEN_HEIGHT,
    },
    ["16_9_iPhone5"] = {
        ["troop_button_startX"] = 0.08715 * SCREEN_WIDTH,
        ["troop_button_startY"] = 0.8234 * SCREEN_HEIGHT,
        ["troop_button_width"] = 0.075784 * SCREEN_WIDTH,
        ["troop_button_height"] = 0.1587 * SCREEN_HEIGHT,
        ["set_troop_startX"] = 0.2 * SCREEN_WIDTH,
        ["set_troop_startY"] = 0.375 * SCREEN_HEIGHT,
        ["set_troop_endX"] = 0.4 * SCREEN_WIDTH,
        ["set_troop_endY"] = 0.15 * SCREEN_HEIGHT,
        ["set_troop_pointX"] = 0.3 * SCREEN_WIDTH,
        ["set_troop_pointY"] = 0.26 * SCREEN_HEIGHT,
        ["set_spell_pointX"] = 0.38 * SCREEN_WIDTH,
        ["set_spell_pointY"] = 0.38 * SCREEN_HEIGHT,
    },
    ["16_9_iPhone6"] = {
        ["troop_button_startX"] = 0.0865 * SCREEN_WIDTH,
        ["troop_button_startY"] = 0.824 * SCREEN_HEIGHT,
        ["troop_button_width"] = 0.075725 * SCREEN_WIDTH,
        ["troop_button_height"] = 0.1587 * SCREEN_HEIGHT,
        ["set_troop_startX"] = 0.2 * SCREEN_WIDTH,
        ["set_troop_startY"] = 0.375 * SCREEN_HEIGHT,
        ["set_troop_endX"] = 0.4 * SCREEN_WIDTH,
        ["set_troop_endY"] = 0.15 * SCREEN_HEIGHT,
        ["set_troop_pointX"] = 0.3 * SCREEN_WIDTH,
        ["set_troop_pointY"] = 0.26 * SCREEN_HEIGHT,
        ["set_spell_pointX"] = 0.38 * SCREEN_WIDTH,
        ["set_spell_pointY"] = 0.38 * SCREEN_HEIGHT,
    },
    ["4_3"] = {
        ["troop_button_startX"] = 0.041721 * SCREEN_WIDTH,
        ["troop_button_startY"] = 0.8542 * SCREEN_HEIGHT,
        ["troop_button_width"] = 0.0842556 * SCREEN_WIDTH,
        ["troop_button_height"] = 0.1328 * SCREEN_HEIGHT,
        ["set_troop_startX"] = 0.142 * SCREEN_WIDTH,
        ["set_troop_startY"] = 0.403 * SCREEN_HEIGHT,
        ["set_troop_endX"] = 0.391 * SCREEN_WIDTH,
        ["set_troop_endY"] = 0.145 * SCREEN_HEIGHT,
        ["set_troop_pointX"] = 0.2866 * SCREEN_WIDTH,
        ["set_troop_pointY"] = 0.2337 * SCREEN_HEIGHT,
        ["set_spell_pointX"] = 0.37 * SCREEN_WIDTH,
        ["set_spell_pointY"] = 0.32 * SCREEN_HEIGHT,
        
        ["set_troop_startX1"] = 0.142 * SCREEN_WIDTH,
        ["set_troop_startY1"] = 0.603 * SCREEN_HEIGHT,
        ["set_troop_endX1"] = 0.391 * SCREEN_WIDTH,
        ["set_troop_endY1"] = 0.855 * SCREEN_HEIGHT,
        ["set_troop_startX2"] = 0.858 * SCREEN_WIDTH,
        ["set_troop_startY2"] = 0.603 * SCREEN_HEIGHT,
        ["set_troop_endX2"] = 0.609 * SCREEN_WIDTH,
        ["set_troop_endY2"] = 0.855 * SCREEN_HEIGHT,
        ["set_troop_startX3"] = 0.609 * SCREEN_WIDTH,
        ["set_troop_startY3"] = 0.145 * SCREEN_HEIGHT,
        ["set_troop_endX3"] = 0.855 * SCREEN_WIDTH,
        ["set_troop_endY3"] = 0.403 * SCREEN_HEIGHT,
        
        ["set_troop_point_tb_X1"] = 0.05 * SCREEN_WIDTH,
        ["set_troop_point_tb_Y1"] = 0.469 * SCREEN_HEIGHT,
        ["set_troop_point_tb_X2"] = 0.54 * SCREEN_WIDTH,
        ["set_troop_point_tb_Y2"] = 0.788 * SCREEN_HEIGHT,
        ["set_troop_point_tb_X3"] = 0.95 * SCREEN_WIDTH,
        ["set_troop_point_tb_Y3"] = 0.469 * SCREEN_HEIGHT,
        ["set_troop_point_tb_X4"] = 0.5 * SCREEN_WIDTH,
        ["set_troop_point_tb_Y4"] = 0.024 * SCREEN_HEIGHT,
        
        -- 大本搜索区域坐标范围 x1,x2, y1,y2
        ["daben_region_1"] = {100,400, 600,800},
        ["daben_region_2"] = {850,1150, 1100,1400},
        ["daben_region_3"] = {1600, 1900, 600, 800},
        ["daben_region_4"] = {850,1150, 20,200},
        
        ["daben_color_7"] = {0xe7c7b5, "10|-7|0xd6ae9c,30|-13|0xbd8239,41|-9|0xffaa42,17|1|0xad7542,31|-1|0xd6b6a5,46|-1|0x6b5952,56|-3|0xdebeb5"},
        ["daben_color_8"] = {0xd6b29c, "14|-10|0xffdbc6,30|-26|0x524942,53|-12|0xceb6ad,65|-2|0xffdfd6,32|-1|0xa56d39,16|1|0x7b5531,45|-3|0xa57142"},
        ["daben_color_9"] = {0x313842, "20|-7|0xbd9e84,37|-15|0x4a494a,55|-6|0x7b7973,71|1|0xceb6a5,42|3|0x313439,26|3|0x292829,37|-3|0x313842"},
        ["daben_color_10"] = {0x943831, "15|-13|0x313029,28|-19|0x635d5a,37|-25|0x313031,47|-19|0x635d6b,55|-16|0x737584,32|-5|0xd6694a,41|-10|0xffc34a"},
        
        ["daben_color_bigger_7"] = {0xf7d3ce, "57|-40|0xf7d3c6,97|-46|0xffaa42,133|-16|0xffae42,153|1|0xe7c7b5,56|11|0x845931,110|11|0xefd3bd,59|39|0xdebead"},
        ["daben_color_bigger_7"] = {0xdebead, "31|-19|0xefcbbd,47|-31|0xbda69c,71|-37|0xffb242,36|7|0xb57942,86|3|0xefcbbd,120|0|0xa59694,102|27|0xf7a239"},
        ["daben_color_bigger_8"] = {0xdebead, "38|-28|0xdeb69c,82|-56|0x6b6163,132|-30|0xd6b6ad,166|-4|0xdec3bd,108|8|0x845931,50|12|0xa57542,67|-8|0xad7142"},
        ["daben_color_bigger_9"] = {0x293042, "60|-27|0x8c7563,104|-52|0x847973,139|-36|0xceb6ad,169|-14|0x94796b,140|3|0x424952,108|-8|0x292829,107|8|0x8c827b"},
        ["daben_color_bigger_10"] = {0x732829, "51|-36|0x393431,104|-70|0x293439,143|-42|0x5a5d63,138|-20|0xffcf5a,154|-14|0x423839,105|-8|0xff824a,66|-8|0xfff78c"},
        
        ["coc_app_color"] = {0xa65a3f, "43|13|0x8f0a12,45|55|0xa3542b,-14|74|0xa75823,-64|44|0xae602e,-10|31|0x180200,2|11|0xf3a368,-32|28|0xfff41e"},
        
        ["bing_weizhi_1"] = {95,1430},
        ["bing_weizhi_2"] = {285,1430},
        ["bing_weizhi_3"] = {445,1430},
        ["bing_weizhi_4"] = {620,1430},
        ["bing_weizhi_5"] = {775,1430},
        ["bing_weizhi_6"] = {950,1430},
        ["bing_weizhi_7"] = {1145,1430},
    },
}
sbattack_vars = sbattack_conf[SCREEN_TYPE]

-- --------------以上为点的配置--------------------------


function ts_frontapp()
    front_app = frontAppBid();
    if front_app ~= COCAPP_IDENTIFIER then
        return false;
    else
        return true;
    end
end

-- 长按
function touchForSeconds(x, y, seconds)
    if ts_frontapp() == false then
        return
    end


    touchDown(1, x, y)
    mSleep(1000 * seconds)
    touchUp(1, x, y)
    mSleep(50)
end

function touchDUAnywhere(x, y)
    touchDown(1, x, y)
    mSleep(50)
    touchUp(1, x, y)
    mSleep(50)
end

function touchDU(x, y)
    if ts_frontapp() == false then
        return
    end


    touchDown(1, x, y)
    mSleep(50)
    touchUp(1, x, y)
    mSleep(50)
end

function cordFromTouch5(x, y)
    return SCREEN_WIDTH * x / 1136, SCREEN_HEIGHT * y / 640
end

function cordFromiPadMini2(x, y)
    return SCREEN_WIDTH * x / 2048, SCREEN_HEIGHT * y / 1536
end

function cordFromiPhone4(x, y)
    return SCREEN_WIDTH * x / 960, SCREEN_HEIGHT * y / 640
end

function is_sameColor(r1, g1, b1, r2, g2, b2)
    return math.abs(r1 - r2) < 10 and math.abs(g1 - g2) < 10 and math.abs(b1 - b2) < 10
end

function is_familiarColor(r1, g1, b1, r2, g2, b2)
    return math.abs(r1 - r2) < 20 and math.abs(g1 - g2) < 20 and math.abs(b1 - b2) < 20
end

function getRealCord(key)

    local type = getScreenType()
    if type == "3_2" then
        local rawx, rawy, r, g, b = conf_3_2[key][1], conf_3_2[key][2], conf_3_2[key][3], conf_3_2[key][4], conf_3_2[key][5]
        local x, y = cordFromiPhone4(rawx, rawy)
        return x, y, r, g, b
    elseif type == "4_3" then
        local rawx, rawy, r, g, b = conf_4_3[key][1], conf_4_3[key][2], conf_4_3[key][3], conf_4_3[key][4], conf_4_3[key][5]
        local x, y = cordFromiPadMini2(rawx, rawy)
        return x, y, r, g, b
    else
        local rawx, rawy, r, g, b = conf_16_9[key][1], conf_16_9[key][2], conf_16_9[key][3], conf_16_9[key][4], conf_16_9[key][5]
        local x, y = cordFromTouch5(rawx, rawy)
        return x, y, r, g, b
    end


--    if DEVICE_TYPE <= 1 then
--        -- iTouch And iPhone
--        local rawx, rawy, r, g, b = conf_16_9[key][1], conf_16_9[key][2], conf_16_9[key][3], conf_16_9[key][4], conf_16_9[key][5]
--        local x, y = cordFromTouch5(rawx, rawy)
--        return x, y, r, g, b
--    else
--        -- iPad
--        local rawx, rawy, r, g, b = conf_4_3[key][1], conf_4_3[key][2], conf_4_3[key][3], conf_4_3[key][4], conf_4_3[key][5]
--        local x, y = cordFromiPadMini2(rawx, rawy)
--        return x, y, r, g, b
--    end
end


function is_okayColorForPointWithKey(key)
    local x, y, r, g, b = getRealCord(key)
    local realR, realG, realB = getColorRGB(x, y)
    return is_sameColor(r, g, b, realR, realG, realB)
end

function is_okayColorForPointWithRGB(x, y, r, g, b)
    local realR, realG, realB = getColorRGB(x, y)
    return is_familiarColor(r, g, b, realR, realG, realB)
end

-- -------------各种动作-----------------
-- 根据key来点击,跳过颜色检查
function touchButtonForKeySkipCheckClor(key)
    local x, y, r, g, b = getRealCord(key)
    touchDU(x, y)
    mSleep(1000)
end

-- 根据key来点击,并且检查颜色
function touchButtonForKey(key)

--    wLog("goblin", "touchButtonForKey:"..key)

    local x, y, r, g, b = getRealCord(key)
    if is_okayColorForPointWithKey(key) then
        touchDU(x, y)
        mSleep(200)
        return true
    end

--    wLog("goblin", "false   touchButtonForKey:"..key)

    return false
end



-- 缩小地图small
function smallShrink()
    touchDU(10, 10)

    number = 5
    touchDown(1, SCREEN_WIDTH / number, SCREEN_HEIGHT / 2)
    touchDown(2, SCREEN_WIDTH * (number - 1) / number, SCREEN_HEIGHT / 2)
    mSleep(50)

    local size = 400

    if SCREEN_HEIGHT == 640 and SCREEN_WIDTH == 960 then
        size = 250
    end


    for i = 1, size, 50 do
        touchMove(1, SCREEN_WIDTH / number + i, SCREEN_HEIGHT / 2)
        touchMove(2, SCREEN_WIDTH * (number - 1) / number - i, SCREEN_HEIGHT / 2)
        mSleep(50)
    end

    touchUp(1, SCREEN_WIDTH / number + size, SCREEN_HEIGHT / 2)
    touchUp(2, SCREEN_WIDTH * (number - 1) / number - size, SCREEN_HEIGHT / 2)

    mSleep(200)
end



-- 缩小地图
function shrink()
    smallShrink()
    smallShrink()
end

-- 放大地图
function expand()
    smallExpand()
    smallExpand()
end


-- 地图上移
function moveUp()
    touchDown(1, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 4)
    mSleep(50)
    for i = 1, SCREEN_HEIGHT / 2, 50 do
        touchMove(1, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 4 + i)
        mSleep(50)
    end
    touchUp(1, SCREEN_WIDTH / 2, SCREEN_HEIGHT * 3 / 4)

    mSleep(200)
end



-- 地图下移
function moveDown()
    touchDown(1, SCREEN_WIDTH / 2, SCREEN_HEIGHT * 3 / 4)
    mSleep(50)
    for i = 1, SCREEN_HEIGHT / 2, 50 do
        touchMove(1, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 4 - i)
        mSleep(50)
    end
    touchUp(1, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 4)

    mSleep(200)
end

-- 回到主屏幕
function backToHome()

    touchButtonForKeySkipCheckClor("rightTopCorner")

    if is_donateOpen() then
        touchButtonForKey("donate_1")
    end

    shrink()
    moveUp()
end


-- 出发干仗
function goBattle()
    mSleep(500)
    touchButtonForKeySkipCheckClor("rightTopCorner")
    mSleep(500)
    touchButtonForKeySkipCheckClor("attackbutton")

--    if touchButtonForKey("attackbutton") == false then
--        return
--    end
    mSleep(200)

--    if touchButtonForKey("findMatchButton") == false then
--        return
--    end
    touchButtonForKeySkipCheckClor("findMatchButton")

    touchButtonForKey("confirmGo")
end

-- 根据位置造兵
function trainDependsOnKey(key)

    local x, y, r, g, b = getRealCord(key)
    while is_okayColorForPointWithKey(key) == true
    do
        touchForSeconds(x, y, 4)
        mSleep(100)
    end
    mSleep(500)

end

-- 根据位置造某种兵多少个
function trainDependsOnKeyWithNumber(key, numb)
    local x, y, r, g, b = getRealCord(key)

    for i=1, numb, 1 do
        touchDU(x, y)
    end

end

-- 根据兵营的次序造兵
function trainDependsOnNumber(num, needClear)

    -- 清除当前兵营的所有兵
    if needClear == 1 then
        trainDependsOnKey("cancelTrainButton")
    end

    -- 1 弓箭, 2 胖子, 3 黄人, 4 胖子
    if num == 1 then
        if needClear ~= 1 then
            trainDependsOnKey("trainBarbarian")
        else
            trainDependsOnKeyWithNumber("trainGiant", 3)
            trainDependsOnKeyWithNumber("trainWallBreaker", 1)
            trainDependsOnKey("trainBarbarian")
        end


    elseif num == 2 then
        if needClear ~= 1 then
            trainDependsOnKey("trainGoblin")
        else
            trainDependsOnKeyWithNumber("trainGiant", 3)
            trainDependsOnKeyWithNumber("trainWallBreaker", 1)
            trainDependsOnKey("trainGoblin")
        end


    elseif num == 3 then

        if needClear ~= 1 then
            trainDependsOnKey("trainAnchor")
        else
            trainDependsOnKeyWithNumber("trainGiant", 3)
            trainDependsOnKeyWithNumber("trainWallBreaker", 1)
            trainDependsOnKey("trainAnchor")
        end

    elseif num == 4 then
        if needClear ~= 1 then
            trainDependsOnKey("trainAnchor")
        else
            trainDependsOnKeyWithNumber("trainGiant", 3)
            trainDependsOnKeyWithNumber("trainWallBreaker", 1)
            trainDependsOnKey("trainAnchor")
        end

    end


end

-- 造兵
function trainSoldier(needCls)

    backToHome()

    touchButtonForKeySkipCheckClor("rightDownBarracks")




    local number = 0
    for i = 1, 10, 1 do
        if is_barracksTraining() then
            number = number + 1


            if number > BARRACKS_NUMBER then
                break
            end
            trainDependsOnNumber(number, needCls)

        end

        if is_spellFactoryTraining() then
            mSleep(200)
            trainDependsOnKey("makeRageSpell")
        end

        -- 切换
        if touchButtonForKey("train_switch_right") == false then
            return
        end
        mSleep(100)
    end

    backToHome()

end


-- countBarracks()  数普通兵营个数
function countBarracks()
    backToHome()

    touchButtonForKeySkipCheckClor("rightDownBarracks")



    -- 先清除所有兵营的兵
    for i = 1, 10, 1 do
        if is_barracksTraining() then
            trainDependsOnKey("cancelTrainButton")
        end
        -- 切换
        if touchButtonForKey("train_switch_right") == false then
            return
        end
        mSleep(100)
    end


    -- 做一个标志位, 数数
    local beginCnt = 0
    local total = 0
    for i = 1, 80, 1 do

        if is_barracksTraining() then
            if beginCnt == 0 then
                beginCnt = 1
                trainDependsOnKey("trainAnchor")
            else
                total = total + 1
                if is_okayColorForPointWithKey("cancelTrainButton") then
                    BARRACKS_NUMBER = total
                    break
                end
            end
        end

        -- 切换
        if touchButtonForKey("train_switch_right") == false then
            return
        end
        mSleep(100)
    end

end



function findKindByKey(thekey)

    x1, y1, color1, placeholder1, placeholder1 = getRealCord(thekey .. "_1")

    posAndColor = ""
    for i=2,4,1 do
        nx, ny, colorn, pn1, pn2 = getRealCord(thekey .. "_" .. i)
        posAndColor = posAndColor .. (nx - x1) .. "|" .. (ny - y1) .. "|" .. string.format("0x%06X",colorn)
        if i ~= 4 then
            posAndColor = posAndColor .. ","
        end
    end

    return findMultiColorInRegionFuzzy( color1, posAndColor, 75, 0, 0, SCREEN_WIDTH - 1, SCREEN_HEIGHT - 1)
end

function collectByKey(key)

    local count = 0
    while true do
        count = count + 1

        local x, y = findKindByKey(key)
        if x == -1 or y == -1 or count > 15 then
            return
        end

        touchDU(x, y)
        mSleep(100)
    end

end

function collectMyResource()
    backToHome()

    collectByKey("goldCoin")
    mSleep(100)
    collectByKey("purpleWater")
    mSleep(100)
    collectByKey("blackWater")
    mSleep(100)
end



function castleRequest()

    if is_okayColorForPointWithKey("castleRequest_1") and is_okayColorForPointWithKey("castleRequest_2") and touchButtonForKey("castleRequest")  then
        mSleep(500)
        touchButtonForKey("castleRequest_YES")
    end

    mSleep(500)

end



function findImage(imageName)

    local leftx, lefty, cc, dd ,ee = getRealCord("reinforce_left")
    local rightx, righty, cc, dd, ee = getRealCord("reinforce_right")

    x, y = findImageInRegionFuzzy(imageName, 80, leftx, lefty, rightx, righty, 0)

    if x ~= -1 and y ~= -1 then        --如果在指定区域找到某图片符合条件
    return true
    end

    return false
end


function moveTalkDown()
    touchDown(1, SCREEN_WIDTH / 5, SCREEN_HEIGHT * 2 / 5)
    mSleep(50)
    for i = 1, SCREEN_HEIGHT / 2, 50 do
        touchMove(1, SCREEN_WIDTH / 5, SCREEN_HEIGHT * 2 / 5 + i)
        mSleep(50)
    end
    touchUp(1, SCREEN_WIDTH / 5, SCREEN_HEIGHT * 9 / 10)

    mSleep(1000)
end

function reinforce()
    backToHome()

    -- open reinforce ui
    if touchButtonForKey("reinforce_open") == false then
        return;
    end

    -- click reinforce tab
    local x, y, r, g, b = getRealCord("reinforce_tab")
    touchDU(x, y)
    mSleep(1000)

    -- move to top
    moveTalkDown()
    mSleep(1000)
    if is_okayColorForPointWithKey("reinforce_btn") then
        local xx, yy, r, g, b = getRealCord("reinforce_btn");
        touchDU(xx, yy)
        mSleep(1000)
        if is_okayColorForPointWithKey("reinforce_ok_1_1") and is_okayColorForPointWithKey("reinforce_ok_1_1") then
            trainDependsOnKey("reinforce_anchor")
        elseif is_okayColorForPointWithKey("reinforce_ok_2_1") and is_okayColorForPointWithKey("reinforce_ok_2_1") then
            trainDependsOnKey("reinforce_anchor")
        elseif is_okayColorForPointWithKey("reinforce_ok_3_1") and is_okayColorForPointWithKey("reinforce_ok_3_1") then
            trainDependsOnKey("reinforce_anchor")
        end
    end
--
--    if is_okayColorForPointWithKey("reinforce_btn") then
--        -- check and donate
--        if pcall(isRandomRequest) then
--            if randomRequestOkay == 1 then
--                local xx, yy, r, g, b = getRealCord("reinforce_btn");
--                touchDUAnywhere(xx, yy)
--                trainDependsOnKey("reinforce_anchor")
--            end
--        end
--    end

    backToHome()
end

-- 在我村庄首页
function doSomethingOnMyHomeLand(looptime)

    remainder = looptime % 5

    if is_barracksFull() then
        trainSoldier(1)
        goBattle()
        return
    elseif remainder == 1 then
        trainSoldier(0)
    elseif remainder == 2 then
        collectMyResource()
    else
        reinforce()
    end



    checkFlag = looptime % 360
    if checkFlag == 359  then
        runFromXX()
    elseif checkFlag == 210 then
        countBarracks()
        trainSoldier(1)
    end

    backToHome()

end


-- -------------各种动作-----------------

-- ---------------新的造兵方式--------------

function n_backToSummary()
    touchButtonForKeySkipCheckClor("n_summary")
end

function n_isNeedRequest()
    n_backToSummary()
    if is_okayColorForPointWithKey("castleRequest_1") and is_okayColorForPointWithKey("castleRequest_2") and touchButtonForKey("castleRequest")  then
        mSleep(500)
        touchButtonForKey("castleRequest_YES")
        mSleep(1000)
        return true
    end
    return false
end


function n_isNeedTrain()
    n_backToSummary()
    for i = 1, 4, 1 do
        local key1, key2 = "n_barrack_avalible_" .. i, "n_barrack_idle_" .. i
        if is_okayColorForPointWithKey(key1) and is_okayColorForPointWithKey(key2) then
            return true
        end
    end
    return false
end

function n_countNumOfBarracks()
    n_backToSummary()
    local numOfBarrack = 0
    for i = 1, 4, 1 do
        local key1, key2 = "n_barrack_avalible_" .. i, "n_barrack_idle_" .. i
        if is_okayColorForPointWithKey(key1) then
            numOfBarrack = numOfBarrack + 1
        end
    end
    return numOfBarrack
end


function n_doTrain(pos, actualOrder, isAppend)
    local key1, key2 = "n_barrack_avalible_" .. pos, "n_barrack_idle_" .. pos
    if is_okayColorForPointWithKey(key1) == false then
        return false
    end

    touchButtonForKeySkipCheckClor(key1)
    
    if setting_iftouben == true then
        if actualOrder == 1 then
            trainDependsOnKey("trainGiant")
        else
            trainDependsOnKey("trainAnchor")
        end
        return true
    end

    if isAppend == false then
        trainDependsOnKey("cancelTrainButton")
        trainDependsOnKeyWithNumber("trainGiant", 3)
        if setting_ifdeadFish == false then
          trainDependsOnKeyWithNumber("trainWallBreaker", 1)
        end
    else
        trainDependsOnKeyWithNumber("trainAnchor", 30)
        return true
    end

    trainDependsOnKeyWithNumber("trainBarbarian", trainBarbarianCount)
    trainDependsOnKey("trainAnchor")
    
--    if actualOrder == 1 then
--        trainDependsOnKey("trainAnchor")
--        trainDependsOnKey("trainBarbarian")
--    elseif actualOrder == 2 then
--        trainDependsOnKey("trainBarbarian")
--    elseif actualOrder == 3 then
--        trainDependsOnKey("trainAnchor")
--        trainDependsOnKey("trainBarbarian")
--    elseif actualOrder == 4 then
--        trainDependsOnKey("trainGoblin")
--        trainDependsOnKey("trainAnchor")
--        trainDependsOnKey("trainBarbarian")
--    end


    return true


end

function n_doTrainSoldier(append)
    n_backToSummary()
    local numOfBarrack = n_countNumOfBarracks()
    local numberOfGaint = 12 / numOfBarrack;
    local numberOfWallBreaker = 4 / numOfBarrack;

    local order = 1
    for i = 1, 4, 1 do
        if n_doTrain(i, order, append) == true then
            order = order + 1
        end
    end

    -- makeSpell
    n_backToSummary()
    local key1 = "n_spellfactory_avalible"
    if is_okayColorForPointWithKey(key1) == false then
        return
    end

    touchButtonForKeySkipCheckClor(key1)
    if setting_ifuseRageSpell == true and setting_ifdeadFish == false and setting_iftouben == false then
      trainDependsOnKey("makeRageSpell")
    end

end


function n_isFullAt(pos)
--      return is_okayColorForPointWithKey("is_full")
    local key1, key2 = "n_barrack_avalible_" .. pos, "n_barrack_idle_" .. pos
    if is_okayColorForPointWithKey(key1) == false then
        return false
    end

    touchButtonForKeySkipCheckClor(key1)

--    return is_okayColorForPointWithKey("fullMark") and is_okayColorForPointWithKey("cancelTrainButton")
    return is_okayColorForPointWithKey("fullMark")
end
function n_isBarrackFull()
    n_backToSummary()
    for i = 1, 4, 1 do
        if n_isFullAt(i) then
            return true
        end
    end
    return false
end

function actionOnHomeLandForTouben(looptime)
    -- 点进兵营
    touchButtonForKeySkipCheckClor("rightDownBarracks")
    -- 如果需要请求支援
    if setting_ifrequest and n_isNeedRequest() then
--        backToHome()
        mSleep(15000)
    end

    -- 如果需要造兵
    if n_isNeedTrain() then
        n_doTrainSoldier(true)
        backToHome()
        return
    end

    -- 如果兵营已满
    if n_isBarrackFull() then
        touchButtonForKeySkipCheckClor("rightTopCorner")
        goBattle()
        return
    end
    
    if needtrain > 1 then
        touchButtonForKeySkipCheckClor("rightTopCorner")
        goBattle()
    end
end

function actionOnHomeLandCommon(looptime)
   
    -- 点进兵营
    touchButtonForKeySkipCheckClor("rightDownBarracks")

    -- 如果需要请求支援
    if setting_ifrequest and n_isNeedRequest() then
--        backToHome()
        mSleep(15000)
    end

    -- 如果兵营已满
    if n_isBarrackFull() then
        n_doTrainSoldier(false)
        touchButtonForKeySkipCheckClor("rightTopCorner")
        goBattle()
        return
    end

    -- 如果需要造兵
    if n_isNeedTrain() then

        n_doTrainSoldier(true)

        backToHome()
        return
    end

    if setting_ifdonate then
        reinforce()
    else
        backToHome()
    end
end


function actionOnHomeLand(looptime)
    if setting_iftouben then
        actionOnHomeLandForTouben(looptime)
    else
        actionOnHomeLandCommon(looptime)
    end
end


-- -------------各种状态-----------------
-- 在loading页面
function is_loadingPage()

    if is_okayColorForPointWithKey("loadpage_1") and is_okayColorForPointWithKey("loadpage_2") then
        return true
    end

    return is_okayColorForPointWithKey("loadpage_3") and is_okayColorForPointWithKey("loadpage_4")
end

-- 在部落站页面
function is_clanWarPage()
    return is_okayColorForPointWithKey("clanwar_1")
--            and is_okayColorForPointWithKey("clanwar_2")
end

-- 捐兵打开
function is_donateOpen()
    return is_okayColorForPointWithKey("donate_1") and is_okayColorForPointWithKey("donate_2")
end


-- barracks 普通兵营造兵页面
function is_barracksTraining()
    return is_okayColorForPointWithKey("barracks_1") and is_okayColorForPointWithKey("barracks_2")
end


-- dark barracks 暗黑兵营造兵页面
function is_darkBarracksTraining()
    return is_okayColorForPointWithKey("darkbarracks_1") and is_okayColorForPointWithKey("darkbarracks_2")
end


-- spell factory 药水工厂造药水页面
function is_spellFactoryTraining()
    return is_okayColorForPointWithKey("spellfactory_1") and is_okayColorForPointWithKey("spellfactory_2")
end


-- 搜索页面
function is_SearchMatch()
    return is_okayColorForPointWithKey("searchmatch")
end

-- 战斗前页面
function is_beforeAttack()
    return is_okayColorForPointWithKey("beforeattack_1") and is_okayColorForPointWithKey("beforeattack_2")
end

-- 战斗后
function is_afterAttack()
    return is_okayColorForPointWithKey("afterattack_1") and is_okayColorForPointWithKey("afterattack_2")
end

-- 战斗后1颗星
function is_afterAttack_1star()
    return is_okayColorForPointWithKey("afterattack_1star_1") and is_okayColorForPointWithKey("afterattack_1star_2")
end

-- 训练营已满
function is_barracksFull()
    backToHome()

    touchButtonForKeySkipCheckClor("rightDownBarracks")

    castleRequest()

    if touchButtonForKey("train_switch_right") == false then
        return false
    end



--    touchButtonForKey("trainAnchor")
    mSleep(1000)


    return is_okayColorForPointWithKey("fullMark") and is_okayColorForPointWithKey("cancelTrainButton")
end

-- 在我的村庄首页
function is_MyHome()
    backToHome()

    mSleep(1000)
    return is_okayColorForPointWithKey("myHomeMark")
end

-- -------------各种状态-----------------



-- --------------sbAttack---------------
buttonWidth, buttonHeight = sbattack_vars["troop_button_width"], sbattack_vars["troop_button_height"]
-- --------------sbAttack初始化----------

BUTTON_POSITIONS = {}
TROOPS_COLORS = {
    ["barbarian"] = {{0.07865, 0.67924, 255, 203, 181}, {0.49456, 0.21802, 255, 247, 49}, {0.54407, 0.35220, 255, 199, 33}},
    ["archer"] = {{0.14813, 0.41928, 140, 40, 82}, {0.49472, 0.26834, 255, 97, 206}, {0.66306, 0.41928, 255, 65, 123}},
    ["goblin"] = {{0.08887, 0.58700, 99, 36, 8}, {0.48498, 0.32704, 181, 247, 107}, {0.72264, 0.36058, 189, 247, 99}},
    ["gaint"] = {{0.32670, 0.41928, 255, 138, 16}, {0.61387, 0.34381, 255, 215, 156}, {0.81192, 0.88050, 165, 105, 99}},
    ["wallbreaker"] = {{0.17832, 0.57861, 82, 65, 66}, {0.58432, 0.64570, 255, 231, 214}, {0.67345, 0.39412, 231, 134, 74}},
    ["king"] = {{0.23805, 0.55345, 222, 190, 90}, {0.47572, 0.56184, 255, 199, 189}, {0.73318, 0.87211, 198, 60, 74}},
    ["queen"] = {{0.31744, 0.28511, 156, 65, 255}, {0.74325, 0.41928, 57, 28, 107}, {0.54520, 0.77148, 132, 138, 82}},
    ["ragespell"] = {{0.46614, 0.31865, 247, 174, 132}, {0.42652, 0.61215, 66, 32, 107}, {0.58497, 0.81341, 214, 109, 247}}
}
NO_TROOPS_COLOR = {0.137517, 0.117622, 57, 60, 57}

function haveTroops(troopType)
    local postion = BUTTON_POSITIONS[troopType]
    if postion == nil then
        return
    end
    local tmpX, tmpY = postion[1] + NO_TROOPS_COLOR[1] * buttonWidth - buttonWidth / 2, sbattack_vars["troop_button_startY"] + NO_TROOPS_COLOR[2] * buttonHeight
    return is_okayColorForPointWithRGB(tmpX , tmpY, NO_TROOPS_COLOR[3], NO_TROOPS_COLOR[4], NO_TROOPS_COLOR[5]) == false
end

function getTroopParam(troopType, dx, dy)
    local troopColors = TROOPS_COLORS[troopType]
    local param = dx .. "|0|" .. string.format("0x%06X", troopColors[2]) .. ",0|" .. dy .. "|" .. string.format("0x%06X", troopColors[3]) .. "," .. dx .. "|" .. dy .. "|" .. string.format("0x%06X", troopColors[4])
    return string.format("0x%06X", troopColors[1]), param
end

function findFirstTroopButtonPosition()
    local dx, dy = math.floor(0.5 + buttonWidth / 4), math.floor(0.5 + buttonHeight / 4)
    local startX, startY, endX, endY = 0, (SCREEN_HEIGHT - buttonHeight * 2), SCREEN_WIDTH / 3, SCREEN_HEIGHT
    mSleep(1000)
    local color, param = getTroopParam("barbarian", dx, dy)
    local tmpX, tmpY = findMultiColorInRegionFuzzy(color, param, 75, startX, startY, endX, endY)
    if tmpX ~= -1 and tmpY ~= -1 then
        return tmpX - dx, tmpY - dy
    end
    return -1, -1
end
-- hehe

function findTroopButtonKind(x, y)
    local dx, dy = math.floor(0.5 + buttonWidth / 4), math.floor(0.5 + buttonHeight / 4)
    for troopType, colors in pairs(TROOPS_COLORS) do
        local troopColors = TROOPS_COLORS[troopType]
        local ok = true
        for i = 1, 3 do
            local tmpX, tmpY, r, g, b = math.floor(0.5 + x + troopColors[i][1] * buttonWidth), math.floor(0.5 + y + troopColors[i][2] * buttonHeight), troopColors[i][3], troopColors[i][4], troopColors[i][5]
            if is_okayColorForPointWithRGB(tmpX, tmpY, r, g, b) == false then
                ok = false
            end
        end
        if ok then
            return troopType
        end
    end
    return -1
end
--
--function setTroopButtonsPosition()
--    local startX, startY = sbattack_vars["troop_button_startX"], sbattack_vars["troop_button_startY"]
--    for i = 1, 11 do
--        local x = startX + (i - 1) * buttonWidth
--        local troopType = findTroopButtonKind(math.floor(0.5 + x), math.floor(0.5 + startY), math.floor(0.5 + x + buttonWidth), math.floor(0.5 + startY + buttonHeight))
--        local otherIndex = 1
--        if troopType ~= -1 then
--            BUTTON_POSITIONS[troopType] = { math.floor(0.5 + x + buttonWidth / 2), math.floor(0.5 + startY + buttonHeight / 2) }
--        elseif BUTTON_POSITIONS["castle"] == nil then
--            BUTTON_POSITIONS["castle"] = { math.floor(0.5 + x + buttonWidth / 2), math.floor(0.5 + startY + buttonHeight / 2) }
--        else
--            BUTTON_POSITIONS["other"..otherIndex] = { math.floor(0.5 + x + buttonWidth / 2), math.floor(0.5 + startY + buttonHeight / 2) }
--            otherIndex = otherIndex + 1
--        end
--    end
--end

-- 简单版
function setTroopButtonsPosition()
--    if is_okayColorForPointWithKey("gd_barbarian") == true then
        BUTTON_POSITIONS["barbarian"] = sbattack_vars["bing_weizhi_1"]
        BUTTON_POSITIONS["archer"] = sbattack_vars["bing_weizhi_2"]
        BUTTON_POSITIONS["gaint"] = sbattack_vars["bing_weizhi_3"]
        BUTTON_POSITIONS["castle"] = sbattack_vars["bing_weizhi_4"]
        BUTTON_POSITIONS["king"] = sbattack_vars["bing_weizhi_5"]
        BUTTON_POSITIONS["queen"] = sbattack_vars["bing_weizhi_6"]
--    else 
--        BUTTON_POSITIONS["archer"] = sbattack_vars["bing_weizhi_1"]
--        BUTTON_POSITIONS["gaint"] = sbattack_vars["bing_weizhi_2"]
--        BUTTON_POSITIONS["castle"] = sbattack_vars["bing_weizhi_3"]
--        BUTTON_POSITIONS["king"] = sbattack_vars["bing_weizhi_4"]
--        BUTTON_POSITIONS["queen"] = sbattack_vars["bing_weizhi_5"]
--    end
end

function setTroops(troopType, count, startX, startY, endX, endY)
    local dx, dy = (endX - startX) / (count - 1), (endY - startY) / (count - 1)
    local postion = BUTTON_POSITIONS[troopType]
    if postion == nil then
        return
    end
    local troopButtonX, troopButtonY = postion[1], postion[2]

    if troopButtonX > 0 and troopButtonY > 0 then
        touchDU(troopButtonX, troopButtonY)
        local x, y = -1, -1
        for i = 1, count do
            x = startX + dx * i
            y = startY + dy * i
            touchDU(x, y)
        end
    end
end

function setOneItem(itemType, x, y)
    local postion = BUTTON_POSITIONS[itemType]
    if postion == nil then
        return
    end
    local itemButtonX, itemButtonY = postion[1], postion[2]

    if itemButtonX > 0 and itemButtonY > 0 then
        touchDU(itemButtonX, itemButtonY)
        touchDU(x, y)
    end
end

function setItem(itemType, count, x, y)
    local postion = BUTTON_POSITIONS[itemType]
    if postion == nil then
        return
    end
    local itemButtonX, itemButtonY = postion[1], postion[2]

    if itemButtonX > 0 and itemButtonY > 0 then
        touchDU(itemButtonX, itemButtonY)
        for i = 1, count do
            touchDU(x, y)
        end
    end
end

function setTroopsAt(area, troopType, count)
    local startX, startY, endX, endY, x, y = 0, 0, 0, 0, 0, 0
    if area == 0 then
        startX = sbattack_vars["set_troop_startX"]
        startY = sbattack_vars["set_troop_startY"]
        endX = sbattack_vars["set_troop_endX"]
        endY = sbattack_vars["set_troop_endY"]
    end
    if area == 1 then
        startX = sbattack_vars["set_troop_startX1"]
        startY = sbattack_vars["set_troop_startY1"]
        endX = sbattack_vars["set_troop_endX1"]
        endY = sbattack_vars["set_troop_endY1"]
    end
    if area == 2 then
        startX = sbattack_vars["set_troop_startX2"]
        startY = sbattack_vars["set_troop_startY2"]
        endX = sbattack_vars["set_troop_endX2"]
        endY = sbattack_vars["set_troop_endY2"]
    end
    if area == 3 then
        startX = sbattack_vars["set_troop_startX3"]
        startY = sbattack_vars["set_troop_startY3"]
        endX = sbattack_vars["set_troop_endX3"]
        endY = sbattack_vars["set_troop_endY3"]
    end
    setTroops(troopType, count, startX, startY, endX, endY)
end

function setAllTroops(tmpX, tmpY)
    local troopTypes = {"barbarian", "archer", "goblin", "wallbreaker", "gaint"}
    for j, troopType in pairs(troopTypes) do
        local c, max = 1, 40
        while haveTroops(troopType) do
            for i = 1, 5 do
                if BUTTON_POSITIONS[troopType] ~= nil then
                    setItem(troopType, 5, tmpX, tmpY)
                end
            end
            mSleep(500)
            c = c + 1
        end
    end
end

function attack()
    local setTroopPointX, setTroopPointY = sbattack_vars["set_troop_pointX"], sbattack_vars["set_troop_pointY"]
    local setSpellPointX, setSpellPointY = sbattack_vars["set_spell_pointX"], sbattack_vars["set_spell_pointY"]

    shrink()
    moveUp()
    setItem("gaint", 16, setTroopPointX, setTroopPointY)
    -- setTroopsAt(0, "gaint", 12)
    setTroopsAt(0, "barbarian", 15)
    mSleep(700)
    setItem("wallbreaker", 2, setTroopPointX, setTroopPointY)
    setTroopsAt(0, "archer", 20)
    setItem("wallbreaker", 2, setTroopPointX, setTroopPointY)
    setOneItem("castle", setTroopPointX, setTroopPointY)
    setOneItem("king", setTroopPointX, setTroopPointY)
    setOneItem("queen", setTroopPointX, setTroopPointY)
    setItem("wallbreaker", 2, setTroopPointX, setTroopPointY)

    setTroopsAt(0, "barbarian", 10)
    setTroopsAt(0, "archer", 15)

    if setting_ifuseRageSpell == true then
        setOneItem("ragespell", setSpellPointX, setSpellPointY)
    end

    setTroopsAt(0, "goblin", 10)

    for i=1,5 do
        setItem("barbarian", 5, setTroopPointX, setTroopPointY)
        mSleep(500)
        setItem("archer", 5, setTroopPointX, setTroopPointY)
        mSleep(500)
        setItem("goblin", 5, setTroopPointX, setTroopPointY)
        mSleep(500)
    end

    setOneItem("king", -1, -1)
    setOneItem("queen", -1, -1)

    for i=1,6 do
        setTroopsAt(0, "barbarian", 6)
        setTroopsAt(0, "archer", 8)
        setTroopsAt(0, "goblin", 6)
    end

    -- setAllTroops(setTroopPointX, setTroopPointY)
end



function attackDeadFish()
    local setTroopPointX, setTroopPointY = sbattack_vars["set_troop_pointX"], sbattack_vars["set_troop_pointY"]
    local setSpellPointX, setSpellPointY = sbattack_vars["set_spell_pointX"], sbattack_vars["set_spell_pointY"]

    shrink()
    moveUp()
    setItem("gaint", 3, setTroopPointX, setTroopPointY)
    mSleep(1000)
--    setTroopsAt(0, "gaint", 3) 
    setTroopsAt(0, "barbarian", 16)
    setOneItem("king", setTroopPointX, setTroopPointY)
    setTroopsAt(0, "archer", 15)
    setOneItem("castle", setTroopPointX, setTroopPointY)
    setOneItem("queen", setTroopPointX, setTroopPointY)
    
    for i=1,3 do
--    设置胖子是5个，实际效果是出3个，正好
      setTroopsAt(i, "gaint", 5)
      mSleep(1000)
      setTroopsAt(i, "barbarian", 16)
      setTroopsAt(i, "archer", 21)
    end
    
    mSleep(500)
    setOneItem("king", -1, -1)
    setOneItem("queen", -1, -1)
    setOneItem("king", 1, 1)
    setOneItem("queen", 1, 1)

    for i=1,3 do  
      setTroopsAt(1, "barbarian", 10)
      setTroopsAt(2, "barbarian", 10)
      setTroopsAt(3, "barbarian", 10)
      setTroopsAt(1, "archer", 10)
      setTroopsAt(2, "archer", 10)
      setTroopsAt(3, "archer", 10)
    end
    
    -- setAllTroops(setTroopPointX, setTroopPointY)
end


function attackToubenWithRegion(r, gaint, isArround)
    shrink()
    moveUp()
    local rx = sbattack_vars["set_troop_point_tb_X"..r]
    local ry = sbattack_vars["set_troop_point_tb_Y"..r]
    if r == 2 then
        mSleep(1000)
        expand()
    end
    
    if gaint == true then
        setItem("gaint", 1, rx, ry)
        mSleep(1000)
        setItem("gaint", 2, rx, ry)
        setOneItem("castle", rx, ry)
        setOneItem("king", rx, ry)
        setOneItem("queen", rx, ry)
        setItem("archer", 20, rx, ry)
        mSleep(10000)
        for i=1,10,1 do
            res = checkFightingResult(1)
            if res == true then
                shrink()
                return true
            end
            if i <= 5 then
                setItem("gaint", 2, rx, ry)
                mSleep(500)
                setItem("barbarian", 2, rx, ry)
                setItem("archer", 15, rx, ry)
                mSleep(3000)
            end
        end
        needtrain = 1
    elseif needtrain % 5 == 0 and isArround == false then
        setItem("gaint", 2, rx, ry)
        setItem("archer", 10, rx, ry)
        needtrain = 1
    else
        setItem("archer", 10, rx, ry)
    end
    
    shrink()
    return true
end
function attackToubenAround() 
--    attackToubenWithRegion(1, false, 5)
--    attackToubenWithRegion(3, false, 5)
    attackToubenWithRegion(4, false, true)
    attackToubenWithRegion(2, false, true)
end

function endFightAndGoHome()
     touchButtonForKey("end_fight")
     mSleep(2000)
     touchButtonForKey("confirm_end_fight")
     mSleep(2000)
     touchButtonForKey("afterattack_1")
end

function attackTouben() 
    shrink()
    moveUp()
    needtrain = needtrain + 1
    local r = findDabenRegion()
    if r == 0 then
        -- 不在区域内
        if touchButtonForKey("find_next") == false then
              mSleep(1000) 
              touchButtonForKey("end_fight")
        end
        return
    elseif r == 2 or r == 4 then
--        -- 2,4区域识别不准，保险起见，全部干
        attackToubenAround()
    else
        -- 10个弓箭手干
        attackToubenWithRegion(r, false, false)
    end
    
    if r > 0 then
        local res = checkFightingResult(40)
        if res == false then
            --没干死，上胖子援军
            attackToubenWithRegion(r, true)
        end
    end
--    endFightAndGoHome()
end

function checkFightingResult(sec)
    for i=1,sec, 1 do
        mSleep(1000)
        if is_afterAttack_1star() == true then
            endFightAndGoHome()
            return true
        end
    end
    return false
end

function sbAttack()
    setTroopButtonsPosition()
    if setting_iftouben == true then
      attackTouben()
    elseif setting_ifdeadFish == true then
      attackDeadFish()
    else
      attack()
    end
end

-- --------------sbAttack---------------


-- ---------------check if random request ------

local b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'

function encodeURI(w)
    --    s = string.gsub(s, "([^%w%.%- ])", function(c) return string.format("%%%02X", string.byte(c)) end)
    --    return string.gsub(s, " ", "+")
    local pattern="[^%w%d%._%-%* ]"
    local s=string.gsub(w,pattern,function(c)
        local c=string.format("%%%02X",string.byte(c))
        return c
    end)
    s=string.gsub(s," ","+")
    return s
end

-- encoding
function enc(data)
    return ((data:gsub('.', function(x)
        local r,b='',x:byte()
        for i=8,1,-1 do r=r..(b%2^i-b%2^(i-1)>0 and '1' or '0') end
        return r;
    end)..'0000'):gsub('%d%d%d?%d?%d?%d?', function(x)
        if (#x < 6) then return '' end
        local c=0
        for i=1,6 do c=c+(x:sub(i,i)=='1' and 2^(6-i) or 0) end
        return b:sub(c+1,c+1)
    end)..({ '', '==', '=' })[#data%3+1])
end

-- decoding
function dec(data)
    data = string.gsub(data, '[^'..b..'=]', '')
    return (data:gsub('.', function(x)
        if (x == '=') then return '' end
        local r,f='',(b:find(x)-1)
        for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and '1' or '0') end
        return r;
    end):gsub('%d%d%d?%d?%d?%d?%d?%d?', function(x)
        if (#x ~= 8) then return '' end
        local c=0
        for i=1,8 do c=c+(x:sub(i,i)=='1' and 2^(7-i) or 0) end
        return string.char(c)
    end))
end


function isOkayWord(word)
    local from, to = string.find(word, "部落");
    if from ~= nil then
        return false
    end
    local from, to = string.find(word, "随便");
    if from ~= nil then
        return true
    end
    local from, to = string.find(word, "随意");
    if from ~= nil then
        return true
    end
    local from, to = string.find(word, "救命");
    if from ~= nil then
        return true
    end
    local from, to = string.find(word, "增援");
    if from ~= nil then
        return true
    end
    local from, to = string.find(word, "弓");
    local from2, to2 = string.find(word, "不");
    if from ~= nil and from2 == nil then
        return true
    end

    return false
end


randomRequestOkay = 0
function isRandomRequest()
    randomRequestOkay = 0
    if unexpected_condition then error() end
    local leftx, lefty, cc, dd ,ee = getRealCord("reinforce_left")
    local rightx, righty, cc, dd, ee = getRealCord("reinforce_right")
    snapshot("d_o_n_c_o_c.jpg", leftx, lefty, rightx, righty, 0.5);

    local input = io.open("/var/mobile/Media/TouchSprite/res/d_o_n_c_o_c.jpg")
    local dat = input:read("*all");
    local base64ImageStr = enc(dat)
    base64ImageStr = encodeURI(base64ImageStr);

    --采用 cjson 构造请求头部 json
    local sz = require("sz")
    local cjson = sz.json
    local http = sz.i82.http
    headers = {}
    headers['Content-Type'] = 'application/x-www-form-urlencoded'
    headers['apikey'] = '1fc88a3327149202a26013c842a51c6c'
    headers_send = cjson.encode(headers)
    --采用 cjson 构造请求内容，并进行 escape
    post = {}
    post['fromdevice'] = 'pc'
    post['clientip'] = '10.10.10.0'
    post['detecttype'] = 'LocateRecognize'
    post['languagetype'] = 'CHN_ENG'
    post['imagetype'] = '1'
    post['image'] = base64ImageStr
    post_send = cjson.encode(post)

    post_escaped = http.build_request(post_send)


    postString = "fromdevice=pc&clientip=10.10.10.0&detecttype=LocateRecognize&languagetype=CHN_ENG&imagetype=1&image=" .. base64ImageStr
    status_resp, headers_resp, body_resp = http.post("http://apis.baidu.com/idl_baidu/baiduocrpay/idlocrpaid", 5, headers_send, postString)

    randomRequestOkay = 0
    if status_resp ~= nil then
        if status_resp == 200 then
            local tmpJson = cjson.decode(body_resp);
            local ocrArr = tmpJson['retData']
            if ocrArr == nil then
                randomRequestOkay = 0
                return false
            end

            local ocrOne = ocrArr[1]
            if ocrOne == nil then
                randomRequestOkay = 0
                return false
            end

            local word = ocrOne['word']
            if word == nil then
                randomRequestOkay = 0
                return false
            end

            if isOkayWord(word) then
                randomRequestOkay = 1
                return true
            end

            randomRequestOkay = 0
            return false

        end
    end

    randomRequestOkay = 0
    return false
end

-- ---------------check if random request ------


-- -------------run from xxzhushou------------

function okayCocText(word)
    local from, to = string.find(word, "部落冲突");
    if from ~= nil then
        return true
    end

    return false
end

function okayCoc(leftx, lefty, rightx, righty)

--    wLog("goblin",  leftx .."  " .. lefty .. "   ".. rightx .." " .. righty)
--    local imgName = "coctext" .. os.time() .. ".jpg"
    local imgName = "coctext.jpg"
    snapshot(imgName, leftx, lefty, rightx, righty, 0.5);

    local input = io.open("/var/mobile/Media/TouchSprite/res/" .. imgName)
    local dat = input:read("*all");
    local base64ImageStr = enc(dat)
    base64ImageStr = encodeURI(base64ImageStr);

    --采用 cjson 构造请求头部 json
    local sz = require("sz")
    local cjson = sz.json
    local http = sz.i82.http
    headers = {}
    headers['Content-Type'] = 'application/x-www-form-urlencoded'
    headers['apikey'] = '1fc88a3327149202a26013c842a51c6c'
    headers_send = cjson.encode(headers)
    --采用 cjson 构造请求内容，并进行 escape
    post = {}
    post['fromdevice'] = 'pc'
    post['clientip'] = '10.10.10.0'
    post['detecttype'] = 'LocateRecognize'
    post['languagetype'] = 'CHN_ENG'
    post['imagetype'] = '1'
    post['image'] = base64ImageStr
    post_send = cjson.encode(post)

    post_escaped = http.build_request(post_send)


    postString = "fromdevice=pc&clientip=10.10.10.0&detecttype=LocateRecognize&languagetype=CHN_ENG&imagetype=1&image=" .. base64ImageStr
--    status_resp, headers_resp, body_resp = http.post("http://apis.baidu.com/apistore/idlocr/ocr", 5, headers_send, postString)
    status_resp, headers_resp, body_resp = http.post("http://apis.baidu.com/idl_baidu/baiduocrpay/idlocrpaid", 5, headers_send, postString)

    if status_resp ~= nil then
        if status_resp == 200 then
            local tmpJson = cjson.decode(body_resp)
            
            local ocrArr = tmpJson['retData']
            if ocrArr == nil then
                return false
            end

            local ocrOne = ocrArr[1]
            if ocrOne == nil then
                return false
            end

            local word = ocrOne['word']
            if word == nil then
                return false
            end

            return okayCocText(word)
        end
    end

    return false
end

function getCocTextColation()
    local ax, ay = 144, 509

    if SCREEN_HEIGHT == 640 and SCREEN_WIDTH == 960 then
        -- iphone 4s
        return 144, 509, 280, 548, 140
    elseif SCREEN_HEIGHT == 640 and SCREEN_WIDTH == 1136 then
        -- iphone5 ipod5
        return 144, 509, 280, 548, 140
    elseif SCREEN_HEIGHT == 750 and SCREEN_WIDTH == 1334 then
        -- iphone6
        return 141, 512, 280, 557, 140
    elseif SCREEN_HEIGHT == 1242 and SCREEN_WIDTH == 2208 then
        -- iphone6 plus
        return 222, 765, 429, 832, 140
    elseif SCREEN_HEIGHT == 768 and SCREEN_WIDTH == 1024 then
        -- ipad1/2  ipad mini
        return 67, 255, 145, 278, 70
    elseif SCREEN_HEIGHT == 1536 and SCREEN_WIDTH == 2048 then
        -- ipad retina
        return 141, 513, 277, 556, 140
    end

    return 144, 509, 280, 548, 140

end


startLocationx, startLocationy = -1, -1
--function getStartLocation()
--    startLocationx, startLocationy = -1, -1
--    if unexpected_condition then error() end
--
--    local ax, ay, bx, by, wx = getCocTextColation()
--
--    for i = 0, 10, 1 do
--        local mx, my = ax , ay+ wx * i
--        local nx, ny = bx , by+ wx * i
--
--        if okayCoc(mx, my, nx, ny) then
----            return mx, SCREEN_HEIGHT - 140
----            wLog("goblin",  SCREEN_HEIGHT .."  " .. SCREEN_WIDTH .." " .. my)
----            return SCREEN_HEIGHT - 140, ny
--            startLocationx, startLocationy = SCREEN_HEIGHT - wx / 2, ny
--        end
--
--    end
--end

function findCocXy() 
    local c = "coc_app_color"
    local x,y = findMultiColorInRegionFuzzy(sbattack_vars[c][1], sbattack_vars[c][2],70, 1,1,SCREEN_WIDTH-1,SCREEN_HEIGHT-1)
    return x,y
end

function touchCoc() 
    local x,y = findCocXy()
    if x ~= -1 and y ~= -1 then
        touchDUAnywhere(x,y)
        mSleep(1000)
        return true
    end
    return false
end

function runFromXX()

    flag = deviceIsLock()

    if flag ~= 0 then
        unlockDevice()
    end

    closeApp(COCAPP_IDENTIFIER)
    mSleep(500)
    closeApp(COCXXZHUSHOU_IDENTIFIER)
    mSleep(500)

    init("0", 0)
    runApp(COCXXZHUSHOU_IDENTIFIER)
    mSleep(7000)

    local f = touchCoc()
    if f == true then
       local xx, yy, r, g, b = getRealCord("coc_start_pos");
       mSleep(3000)
       touchDUAnywhere(xx, yy)
    else 
        dialog("无法识别COC，请手动从叉叉启动，进入成功后，再开启脚本，或者将叉叉升级到最新版本", 5)
    end

--    local x, y = getStartLocation()
--    if pcall(getStartLocation) then
--        if startLocationx ~= -1 then
--            touchDUAnywhere(startLocationx, startLocationy)
--        end
--    else
--        dialog("COC not found!", 2)
--    end

    init("0", 2)

--    local zx, zy = findKindByKey("cocLogoXX")
--    mSleep(200)
--    if zx ~= -1 then
--        touchDUAnywhere(zx, SCREEN_HEIGHT - 140)
--    end


--
--    mSleep(1000)
--
--    -- magic code --
--    snapshot("test.png", 800, 500, 900, 600);
--    -- magic code --
--
--    local xx, yy, r, g, b = getRealCord("cocRunXX");
--    touchDUAnywhere(xx, yy)

end
-- -------------run from xxzhushou------------


-- ------------try click alert------------------
function tryClickAlert()
    front_app = frontAppBid();
    if front_app == COCXXZHUSHOU_IDENTIFIER then
        return ;
    end


    touchButtonForKeySkipCheckClor("rightTopCorner")
    local x, y, r, g, b = getRealCord("alertButton_1")
    touchDUAnywhere(x,y);
    local x, y, r, g, b = getRealCord("alertButton_2")
    mSleep(100)
    touchDUAnywhere(x,y);
--    touchButtonForKey("alertButton_2")
end
-- ------------try click alert------------------



function smallExpand()
    touchDown(1, SCREEN_WIDTH*0.22, SCREEN_HEIGHT*0.32)
    mSleep(50)
    touchDown(2, SCREEN_WIDTH*0.78, SCREEN_HEIGHT*0.32)
    mSleep(50)
    touchMove(1, SCREEN_WIDTH*0.05, SCREEN_HEIGHT*0.32)
    mSleep(50)
    touchMove(2, SCREEN_WIDTH*0.95, SCREEN_HEIGHT*0.32)
    mSleep(50)
    touchUp(1, SCREEN_WIDTH*0.05, SCREEN_HEIGHT*0.32)
    mSleep(50)
    touchUp(2, SCREEN_WIDTH*0.95, SCREEN_HEIGHT*0.32)
    mSleep(100)
    touchDown(1, SCREEN_WIDTH*0.22, SCREEN_HEIGHT*0.68)
    touchMove(1, SCREEN_WIDTH*0.22, SCREEN_HEIGHT*0.18)
    mSleep(50)
    touchUp(1, SCREEN_WIDTH*0.22, SCREEN_HEIGHT*0.18)
    mSleep(50)
end

function findDabenXy() 
    for i=7,10,1 do
        local c = "daben_color_"..i
        mSleep(200)
        local x,y = findMultiColorInRegionFuzzy(sbattack_vars[c][1], sbattack_vars[c][2],70, 1,1,SCREEN_WIDTH-1,SCREEN_HEIGHT-1)
        if x ~= -1 and y ~= -1 then
            return x,y
        end
    end
  return 0,0
end

function findDabenXyBigger() 
    expand()
    for i=7,10,1 do
        local c = "daben_color_bigger_"..i
        mSleep(200)
        local x,y = findMultiColorInRegionFuzzy(sbattack_vars[c][1], sbattack_vars[c][2],70, 1,1,SCREEN_WIDTH-1,SCREEN_HEIGHT-1)
        if x ~= -1 and y ~= -1 then
            shrink()
            return x,y
        end
    end
    shrink()
  return 0,0
end
-- 肯定会返回，0-4
function findDabenRegion()
  local x,y = findDabenXy()
  if x > 0 and y > 0 then
      for i=1,4,1 do
        local k = "daben_region_"..i
        if x > sbattack_vars[k][1] and x < sbattack_vars[k][2] and y > sbattack_vars[k][3] and y < sbattack_vars[k][4] then
          return i
        end
      end
      return 0
  else
      x, y = findDabenXyBigger()
      if x > 0 and y > 0 then
          return 2
      else 
          return 4
      end
  end
--  -- 没找到
--  return -1
end

-- 无限大循环

-- 判断设备类型
--local type = getScreenType()
--if type == "3_2" then
--    dialog("抱歉,不支持当前小屏幕设备!当前支持所有16:9的iPhone,iPod和所有iPad", 0)
--    lua_exit()
--end
-- 判断设备类型

-- 选项设置  --
function setting()
    init("0", 0)
    local sz = require("sz")
    local json = sz.json
    local w,h = getScreenSize();
    MyTable = {
        ["style"] = "default",
        ["width"] = 4 * w / 5,
        ["height"] = 3 * h / 5,
        ["config"] = "save_600.dat",
        ["timer"] = 20,
        views = {
            {
                ["type"] = "Label",
                ["text"] = "COC打鱼小王子设置",
                ["size"] = 25,
                ["align"] = "center",
                ["color"] = "0,0,255",
            },
            {
                ["type"] = "Label",
                ["text"] = "常用选项",
                ["size"] = 18,
                ["align"] = "left",
                ["color"] = "0,0,0",
            },
            
            {
                ["type"] = "CheckBoxGroup",
                ["list"] = "我要捐兵,请求支援",
                ["select"] = "2",
            },
            {
                ["type"] = "RadioGroup",
                ["list"] = "死鱼模式(设置采集器为10-12w，总15w，只支持ipad和mini),偷本模式(设置大本营据边缘4，现在本外置少不建议用)",
                ["select"] = "1",
            },
            
            isArray = true
        }
    }
    local MyJsonString = json.encode(MyTable);
    ret, input_common, input_attack = showUI(MyJsonString);

    if ret == 0 then
        lua_exit()
    end


    if input_common ~= nil then
        local from, to = string.find(input_common, "0");
        if from ~= nil then
            setting_ifdonate = true
        else
            setting_ifdonate = false
        end
        
        local from, to = string.find(input_common, "1");
        if from ~= nil then
            setting_ifrequest = true
        else
            setting_ifrequest = false
        end
        
        local from, to = string.find(input_common, "2");
        if from ~= nil then
            setting_ifuseRageSpell = true
        else
            setting_ifuseRageSpell = false
        end
    else
        setting_ifdeadFish = false
    end
    
    if input_attack ~= nil then
        local from, to = string.find(input_attack, "0");
        if from ~= nil then
            setting_ifdeadFish = true
        else
            setting_ifdeadFish = false
        end
        
        local from, to = string.find(input_attack, "1");
        if from ~= nil then
            setting_iftouben = true
        else
            setting_iftouben = false
        end
    else
        setting_ifdeadFish = false
    end

--    dialog(setting_campDegree .. "_" .. tostring(setting_ifdonate) .. " _" .. tostring(setting_ifrequest) .. "_" .. tostring(setting_ifuseRageSpell),3)
--    lua_exit()

    init("0", 2)
end
-- 选项设置  --

setting()


math.randomseed(os.time())
loopCnt = 0
--closeApp(COCAPP_IDENTIFIER)
lastAttackLoop = -100
StuckCnt = 0

dialog("请打开叉叉助手，并确认COC运行时，Home键在屏幕左边", 3)
while true do

    resetIDLETimer()

    if loopCnt > 0 then
--        mSleep(math.random(7, 10) * 1000)
        mSleep(10*1000)
        -- alertButton每30s左右点击一次
        if loopCnt % 3 == 0 then
          tryClickAlert()
        end
    end


    loopCnt = loopCnt + 1
    if loopCnt >= 20000 then
        loopCnt = 1
    end

    if ts_frontapp() == false then
        runFromXX()
    elseif is_loadingPage() then
        StuckCnt = StuckCnt + 1
        -- loading卡死
        if StuckCnt > 300 then
            StuckCnt = 0
            runFromXX()
        end
    elseif is_SearchMatch() then
        StuckCnt = StuckCnt + 1

        -- 防止搜索卡死
        if StuckCnt > 300 then
            StuckCnt = 0
            runFromXX()
        end

    elseif is_afterAttack() then
        touchButtonForKey("afterattack_1")
        mSleep(3000)
        backToHome()
--        trainSoldier(0)
    elseif is_beforeAttack() then
        if loopCnt - lastAttackLoop > 2 then
            sbAttack()
        elseif setting_iftouben == true then
            sbAttack()
        end
        lastAttackLoop = loopCnt

    elseif is_clanWarPage() then
            touchButtonForKeySkipCheckClor("returnHomeButton")
    elseif is_MyHome() then
        StuckCnt = 0
--        doSomethingOnMyHomeLand(loopCnt)
        actionOnHomeLand(loopCnt)
    else
        StuckCnt = StuckCnt + 1
        -- 防止其他傻逼情况卡主
        if StuckCnt > 300 then
            StuckCnt = 0
            runFromXX()
        end
    end
end

